<?php

namespace app\admin\controller;

use app\model\AgentCode;
use app\model\MemberAutonym;
use think\exception\ValidateException;
use app\model\Technical;
use app\model\TechnicalLevel;
use app\model\Agent;
use app\model\Member;
use app\model\Store;
use app\model\Operatingcity;
use app\model\OperatingcityLevel;
use app\model\OperatingcityType;
use app\model\RegisterField;
use app\model\Area;
use app\model\MemberAuthGroup;
use app\model\Category;
use app\model\StoreCate;
use app\model\Users;

class AutonymController extends Base
{
	function getModel()
	{
		$ptype = $this->getPath()[1];
		if ($ptype == 'technical') {
			return new Technical;
		} else if ($ptype == 'agent') {
			return new Agent;
		} else if ($ptype == 'member') {
			return new Member;
		} else if ($ptype == 'operatingcity') {
			return new Operatingcity;
		} else if ($ptype == 'store') {
			return new Store;
		}
	}
	function getPath()
	{
		$path = input('post.path', '', 'serach_in');
		$tmppath = explode('/', $path);
		$con = input('con');
		if (!empty($con)) {
			$tmppath[1] = $con;
		}
		return $tmppath;
	}

	function index()
	{
		$weid = weid();
		$model = new MemberAutonym();
        $keyword = trim(input('post.keyword', '', 'serach_in'));
        $status = input('post.status', '', 'serach_in');
        $query = $model->where(['weid'=>$weid]);
        if (!empty($keyword)) {
            $query = $query->where('name|mobile', 'like', '%' . $keyword . '%');
        }
        if(!empty($status)){
            $query = $query->where(['status'=>$status]);
        }
		$res = $query->with(['member'])->order('id desc')
			->paginate(getpage())
			->toArray();

//		if (!empty($res['data'])) {
//			foreach ($res['data'] as &$vo) {
//
//				$vo['province_id'] = $vo['province_name'] . $vo['city_name'] . $vo['district_name'];
//
//				$vo['create_time'] = time_format($vo['create_time']);
//			}
//		}
		$data['data'] = $res;
		
		return $this->json($data);
	}
	function setSearch()
	{
		$keyword = trim(input('post.keyword', '', 'serach_in'));
		$status = input('post.status', '', 'serach_in');
		$weid = weid();

		if ($this->getPath()[2] == "audit") {
			$status = "0";
		}
		$query = $this->getModel()->where(['weid' => $weid]);

		if ($this->getPath()[1] == "technical") {
			if (!empty($this->sid)) {
				$query->where('sid', $this->sid);
			}
		}
		if ($this->getPath()[1] == "technical" || $this->getPath()[1] == "store") {
			if (!empty($this->ocid)) {
				$Operatingcitydata = Operatingcity::find($this->ocid);
				if ($Operatingcitydata) {
					$Operatingcitydata = $Operatingcitydata->toArray();
	
					if ($Operatingcitydata['areatype'] == 2) {
						$query->where('district_name', $Operatingcitydata['district_name']);
					} elseif ($Operatingcitydata['areatype'] == 1) {
						$query->where('city_name', $Operatingcitydata['city_name']);
					}
				}
			}
		}

		if (!empty($keyword)) {

			if ($this->getPath()[1] == "member") {
				$query->where('nickname|telephone', 'like', '%' . $keyword . '%');
			} elseif ($this->getPath()[1] == "technical") {
				$query->where('title|tel', 'like', '%' . $keyword . '%');
			} elseif ($this->getPath()[1] == "agent") {
				$query->where('title|tel', 'like', '%' . $keyword . '%');
			} elseif ($this->getPath()[1] == "store") {
				$query->where('title|tel', 'like', '%' . $keyword . '%');
			}
		}

		if (!empty($status) || $status === "0") {
			$query->where(['status' => $status]);
		}
		return $query;
	}

	function listUpdate()
	{
		$data = only('id,status');
		if (!$data['id']) throw new ValidateException('参数错误');
		$this->getModel()->update($data);

		return $this->json(['msg' => '操作成功']);
	}

	public function update()
	{
		$id = $this->request->post('id');
        if (!$id) throw new ValidateException('参数错误');
        $info = MemberAutonym::where(['id'=>$id])->find();
		if(!$info){
            throw new ValidateException('数据不存在');
        }
		if($info['status'] != 1){
            throw new ValidateException('数据已经被审核');
        }
		$status = input('status');
		$reason = input('reason');
		if($status == 3 && !$reason){
            throw new ValidateException('驳回审核需填写驳回原因');
        }
			try {
                $info->status = $status;
                if($status == 3){
                    $info->reason = $reason;
                }
                $info->audit_time  = time();
                $info->update_time = time();
                $r = $info->save();
                if($status ==2 && $r){
                   $memberInfo = Member::where(['id'=>$info->uid])->find();
                   $memberInfo->is_autonym = 2;
                   $memberInfo->save();
                   $r = Agent::where(['uid'=>$info->uid])->findOrEmpty();
                   if($r->isEmpty()){
                       Agent::create(['weid'=>weid(),'uid'=>$info->uid,'title'=>$info->name,'tel'=>$info->mobile,'touxiang'=>$memberInfo->userpic,'customtext'=>'N;','create_time'=>time()]);
                       AgentCode::getagent_code($info->uid, weid());
                   }
                }
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '操作成功']);

	}
	public function audit()
	{
		$id = $this->request->post('id');
		$data['id'] = $id;
		$data['update_time'] = time();
		$data['status'] = 1;

		try {
			$this->getModel()->update($data);
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}
		return $this->json(['msg' => '审核成功']);
	}

	function getInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		$infodata = MemberAutonym::where(['id'=>$id])->find();
		return $this->json(['data' => $infodata]);
	}

	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if (!$idx) throw new ValidateException('参数错误');
       $r=  MemberAutonym::destroy(['id' => explode(',', $idx)], true);
//       dump($r);exit();
		return $this->json(['msg' => '操作成功'.$r]);
	}

	function plaudit(){
        $idx =  $this->request->post('id', '', 'serach_in');
        if (!$idx) throw new ValidateException('参数错误');
        $status =  $this->request->post('status');
        $reason =  $this->request->post('reason');
        $data =  MemberAutonym::where(['id' => explode(',', $idx),'status'=>1])->select();
        foreach ($data as $k=>$v){
            $v->status = $status;
            if($status == 3){
                $v->reason = $reason;
            }
            $v->audit_time  = time();
            $v->update_time = time();
            $r = $v->save();
            if($status ==2 && $r){
                $info = $v;
                $memberInfo = Member::where(['id'=>$v->uid])->find();
                $memberInfo->is_autonym = 2;
                $memberInfo->save();
                $res = Agent::where(['uid'=>$v->uid])->findOrEmpty();
                if($res->isEmpty()){
                    Agent::create(['weid'=>weid(),'uid'=>$info->uid,'title'=>$info->name,'tel'=>$info->mobile,'touxiang'=>$memberInfo->userpic,'customtext'=>'N;','create_time'=>time()]);
                    AgentCode::getagent_code($info->uid, weid());
                }
            }
        }
        return $this->json(['msg' => '操作成功'.$r]);
    }
	/*
 	*  导入
 	*/
	public function importData()
	{
		$data = $this->request->post();
		$ptype = $this->getPath()[1];
		$weid = weid();
		$list = [];

		$importField = RegisterField::getimportField($ptype);

		foreach ($data as $k => $v) {

			$info['weid'] = $weid;

			foreach ($importField as $key => $fvo) {

				if ($fvo['inputtype'] == 'text' || $fvo['inputtype'] == 'textarea') {
					if ($fvo['is_sys'] == 1) {
						$info[$fvo['fieldsmingcheng']] = $v[$fvo['viewmingcheng']];
					} else {
						$customtext['text'][$fvo['id']] = $v[$fvo['viewmingcheng']];
					}
				} elseif ($fvo['inputtype'] == 'select') {
					if ($fvo['is_sys'] == 1) {
						$info[$fvo['fieldsmingcheng']] = $v[$fvo['viewmingcheng']];
					} else {
						$customtext['select'][$fvo['id']] = $v[$fvo['viewmingcheng']];
					}
				} elseif ($fvo['inputtype'] == 'radio') {
					if ($fvo['is_sys'] == 1) {
						if ($fvo['fieldsmingcheng'] == "sex") {
							if ($v[$fvo['viewmingcheng']] == '保密') {
								$info[$fvo['fieldsmingcheng']] = 0;
							} elseif ($v[$fvo['viewmingcheng']] == '男') {
								$info[$fvo['fieldsmingcheng']] = 1;
							} elseif ($v[$fvo['viewmingcheng']] == '女') {
								$info[$fvo['fieldsmingcheng']] = 2;
							}
						}
					} else {
						$customtext['radio'][$fvo['id']] = $v[$fvo['viewmingcheng']];
					}
				} elseif ($fvo['inputtype'] == 'radio') {
					if ($fvo['is_sys'] == 1) {
						$info[$fvo['fieldsmingcheng']] = $v[$fvo['viewmingcheng']];
					} else {
						$customtext['radio'][$fvo['id']] = $v[$fvo['viewmingcheng']];
					}
				}
			}

			$info['customtext'] = serialize($customtext);

			$info['regdate'] = time();
			$info['lastdate'] = time();
			$info['create_time'] = time();

			$is_repeat = 0;

			if (empty($is_repeat)) {
				$this->getModel()->create($info);
				//$list[$k] = $info;
			}
		}
		return $this->json(['msg' => '操作成功']);
	}

	function dumpdata()
	{
		$page = $this->request->post('page', 1, 'intval');
		$limit = config('my.dumpsize') ? config('my.dumpsize') : 1000;
		$ptype = $this->getPath()[1];

		$query = $this->setSearch();

		$count = $query->count();

		$res = $query->order('id desc')
			->limit(($page - 1) * $limit, $limit)
			->select()
			->toArray();

		foreach ($res as $key => $val) {
			$res[$key]['sex'] = getItemVal($val['sex'], '[{"key":"男","val":"1","label_color":""},{"key":"女","val":"2","label_color":""}]');
			$res[$key]['status'] = getItemVal($val['status'], '[{"key":"开启","val":"1"},{"key":"关闭","val":"0"}]');
			$res[$key]['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
		}
		$importField = RegisterField::getimportField($ptype);
		$datalist = [];
		if (!empty($res)) {
			foreach ($res as $k => $vo) {

				foreach ($importField as $key => $fvo) {

					if ($fvo['inputtype'] == 'text' || $fvo['inputtype'] == 'textarea') {
						if ($fvo['is_sys'] == 1) {
							$datalist[$k][$fvo['fieldsmingcheng']] = $vo[$fvo['fieldsmingcheng']];
						} else {
							$datalist[$k][$fvo['inputtype'] . $fvo['id']] = iunserializer($vo['customtext'])[$fvo['inputtype']][$fvo['id']];
						}
					} elseif ($fvo['inputtype'] == 'select') {
						if ($fvo['is_sys'] == 1) {
						} else {
							$datalist[$k][$fvo['inputtype'] . $fvo['id']] = iunserializer($vo['customtext'])[$fvo['inputtype']][$fvo['id']];
						}
					} elseif ($fvo['inputtype'] == 'radio') {
						if ($fvo['is_sys'] == 1) {
							if ($fvo['fieldsmingcheng'] == "sex") {
								if ($vo[$fvo['fieldsmingcheng']] == '0') {
									$datalist[$k]['sex'] = '保密';
								} elseif ($vo[$fvo['fieldsmingcheng']] == '1') {
									$datalist[$k]['sex'] = '男';
								} elseif ($vo[$fvo['fieldsmingcheng']] == '1') {
									$datalist[$k]['sex'] = '女';
								}
							} else {
								$datalist[$k][$fvo['fieldsmingcheng']] = $vo[$fvo['fieldsmingcheng']];
							}
						} else {
							$datalist[$k][$fvo['inputtype'] . $fvo['id']] = iunserializer($vo['customtext'])[$fvo['inputtype']][$fvo['id']];
						}
					} elseif ($fvo['inputtype'] == 'radio') {
						if ($fvo['is_sys'] == 1) {
							$datalist[$k][$fvo['fieldsmingcheng']] = $vo[$fvo['fieldsmingcheng']];
						} else {
							$datalist[$k][$fvo['inputtype'] . $fvo['id']] = iunserializer($vo['customtext'])[$fvo['inputtype']][$fvo['id']];
						}
					}
					//$ii = $key;
				}
			}
		}

		foreach ($importField as $key => $vo) {
			$data['header'][$key] = $vo['viewmingcheng'];
		}
		//var_dump($datalist);
		//var_dump($res);

		$data['percentage'] = ceil($page * 100 / ceil($count / $limit));
		$data['filename'] = '数据.' . config('my.dump_extension');
		$data['data'] = $datalist;
		return $this->json($data);
	}
	public function get_idbytitle($list, $title)
	{
		foreach ($list as  $v) {
			if ($v['key'] == $title) {
				return $v['val'];
			}
		}
		return 0;
	}
	public function get_idbyarea_name($list, $area_name)
	{
		foreach ($list as  $v) {
			if ($v['area_name'] == $area_name) {
				return $v['area_id'];
			}
		}
		return 0;
	}
}
